package com.sisyphus.spinach.network;

import android.util.Log;


import com.sisyphus.spinach.core.INetTask;
import com.sisyphus.spinach.core.model.IResponse;
import com.sisyphus.spinach.network.exceptions.ServeResponseException;

import androidx.annotation.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

public class ResponseObserver<T, V extends INetTask.View<T>> implements Observer<IResponse<T>> {

    private final INetTask.View<T> mView;

    private final INetTask.Presenter<T, V> mPresenter;

    public ResponseObserver(
            @NonNull INetTask.View<T> view,
            @NonNull INetTask.Presenter<T, V> presenter
    ) {

        mView = view;
        mPresenter = presenter;
    }


    @Override
    public void onSubscribe(Disposable d) {
        mView.start();
        mPresenter.add(d);
    }


    @Override
    public void onNext(IResponse<T> t) {
        if (t == null) {
            onError(new NullPointerException("后台返回的数据是null, onNext(T t)"));
            return;
        }

        if (!t.isSuccessful()) { // 失败
            onError(new ServeResponseException(t.getMessage(), t.getErrorCode(), t.getData()));

        } else {
            mView.complete();
            mView.success(t.getData());
        }
    }


    @Override
    public void onError(Throwable throwable) {
        mView.complete();

        try {

            mView.failure(throwable);

        } catch (Exception exception) {
//            Log.d("com.sisyphus.spinach", "-------------------start-------------------------");
//            throwable.printStackTrace();
//            exception.printStackTrace();
//            Log.d("com.sisyphus.spinach", "--------------------end--------------------------");
        }
    }


    @Override
    public void onComplete() {

    }

}
